#!/usr/bin/env bash
set -euo pipefail

# Build a standalone binary for Kylin (银河麒麟) v10 using PyInstaller.
# IMPORTANT: Run this script ON the Kylin machine with Python 3.12.
# PyInstaller cannot cross-compile from macOS to Linux.

ROOT_DIR="$(cd "$(dirname "$0")" && pwd)"

cd "$ROOT_DIR"

PY_CMD="python3"
if command -v python3.12 >/dev/null 2>&1; then
  PY_CMD="python3.12"
fi

if [ ! -d .venv ]; then
  "$PY_CMD" -m venv .venv
fi
# shellcheck disable=SC1091
source .venv/bin/activate

pip install -U pip wheel setuptools
pip install -r requirements.txt
pip install pyinstaller==6.11.1 python-dotenv

# Ensure package is importable when frozen
export PYTHONPATH="$ROOT_DIR:${PYTHONPATH:-}"

OUTDIR="$ROOT_DIR/dist"
mkdir -p "$OUTDIR"

# One-file mode for easier distribution; change to --onedir if you prefer a folder
pyinstaller \
  --clean \
  --name textlabel-server \
  --onefile \
  --collect-all psycopg \
  --collect-binaries psycopg \
  --hidden-import app.main \
  --hidden-import app.db \
  --hidden-import app.redis_client \
  --hidden-import app.schemas \
  --hidden-import app.routers.labels \
  --hidden-import app.routers.texts \
  --hidden-import app.routers.annotations \
  --hidden-import app.routers.export_import \
  --add-data "app:app" \
  --collect-all app \
  --collect-submodules app \
  --exclude-module tests \
  --exclude-module tkinter \
  --exclude-module unittest \
  run_server.py

chmod +x "$ROOT_DIR/dist/textlabel-server" || true

echo "[done] Binary generated at: $ROOT_DIR/dist/textlabel-server"
